package com.example.domain;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

//@Configuration
//@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{

	@Autowired
	private ReaderRepositor readerRepositor;
	
	/**
	 * 个configure()方法指明， “/”（ReadingListController 的方法映射到了该路径）的请求只有经过身份认证且拥有READER角色的用户才能访问。
	 * 其他的 所有请求路径向所有用户开放了访问权限。这里还将登录页和登录失败页（带有一个error属性） 指定到了/login
	 */
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		// TODO Auto-generated method stub
		//设置要求登录着的角色
		http.authorizeRequests()
		.antMatchers("/")
		.access("hasRole('READER')")
		.antMatchers("/**").permitAll()
		.and().formLogin()
		.loginPage("/login").failureUrl("/login?error=true");
	}
	
	/**
	 * configure()方法设置了一个自定义的UserDetailsService，这个服务可以是任意实现了 UserDetailsService的类，用于查找指定用户名的用户
	 */
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		// TODO Auto-generated method stub
		//定义自定义userDetailsService
		auth.userDetailsService(new UserDetailsService() {
			@Override
			public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
				// TODO Auto-generated method stub
				return readerRepositor.findOne(username);
			}
		});
	}
	
}
